Hands-on Exercise 3-2
Programming Animated Statistical Graphics with R
1. Getting Started
1.1 Loading the R packages
1.2 Importing the data
Code chunk to import Data worksheet from GlobalPopulation Excel workbook by using appropriate R package from tidyverse family.
read_xls() of readxl package is used to import the Excel worksheet. mutate_each_() of dplyr package is used to convert all character data type into factor. mutate of dplyr package is used to convert data values of Year field into integer.
Unfortunately, mutate_each_() was deprecated in dplyr 0.7.0. and funs() was deprecated in dplyr 0.8.0. In view of this, we will re-write the code by using mutate_at() as shown in the code chunk below.
Instead of using mutate_at(), across() can be used to derive the same outputs.
2. Animated Data Visualisation: gganimate methods
gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation.
2.1 Building a static population bubble plot
2.2 Building the animated bubble plot
transition_time() of gganimate is used to create transition through distinct states in time (i.e. Year). ease_aes() is used to control easing of aesthetics. The default is linear. Other methods are: quadratic, cubic, quartic, quintic, sine, circular, exponential, elastic, back, and bounce.
Code
ggplot(globalPop, aes(x = Old, y = Young,
size = Population,
colour = Country)) +
geom_point(alpha = 0.7,
show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(title = 'Year: {frame_time}',
x = '% Aged',
y = '% Young') +
transition_time(Year) +
ease_aes('linear') 
3. Animated Data Visualisation: plotly
3.1 Building an animated bubble plot: ggplotly() method
Code
Appropriate ggplot2 functions are used to create a static bubble plot. The output is then saved as an R object called gg. ggplotly() is then used to convert the R graphic object into an animated svg object.
Although show.legend = FALSE argument was used, the legend still appears on the plot. To overcome this problem, theme(legend.position=‘none’) should be used as shown in the plot and code chunk below.
Code
gg <- ggplot(globalPop,
aes(x = Old,
y = Young,
size = Population,
colour = Country)) +
geom_point(aes(size = Population,
frame = Year),
alpha = 0.7) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(x = '% Aged',
y = '% Young') +
theme(legend.position='none')
ggplotly(gg)